<?php
require_once(dirname(__file__)."/../../include/config.php");
require_once(YIQIUINC.'/weibo/sina.php');
require_once(DEDEMEMBER."/config.php");

if($cfg_ml->IsLogin())
{
    ShowMsg('你已经登陆系统，无需重新注册！', '/user');
    exit();
}


$code = request("code",'');
$login_row = $dsql->GetOne("SELECT * FROM yiqiu_login_set");
$login_infos = unserialize($login_row['login_infos']);
$o=new sinaPHP($login_infos['weibo']['appkey'], $login_infos['weibo']['appsecret']);
$result=$o->access_token($login_infos['weibo']['callback'],$code);

$sina=new sinaPHP($login_infos['weibo']['appkey'], $login_infos['weibo']['appsecret'], $result['access_token']);
$userinfo = $sina->show_user_by_id($result['uid']);
if(empty($userinfo['id'])) die("登录失败");
$userid = "s".$userinfo['id'];
$uname = $userinfo['name'];
if($cfg_soft_lang == 'gb2312')
{
	$uname = utf82gb($uname);
}

$face = $userinfo['avatar_large'];

$memInfo = $dsql->GetOne("SELECT * FROM #@__member WHERE `userid` = '{$userid}'");
$jointime = time();
$logintime = time();
$joinip = GetIP();
$loginip = GetIP();

if(empty($memInfo))
{
	$inQuery = "INSERT INTO `#@__member` (`mtype` ,`userid` ,`uname`  ,`rank` ,
        `matt` ,`face`,`jointime` ,`joinip` ,`logintime` ,`loginip`,`mode`)
       VALUES ('个人','$userid','$uname','10','0','$face','$jointime','$joinip','$logintime','$loginip','weibo'); "; 
     if($dsql->ExecuteNoneQuery($inQuery))
     {
            $mid = $dsql->GetLastID();
			//写入默认统计数据
            $membertjquery = "INSERT INTO `#@__member_tj` (`mid`,`article`,`album`,`archives`,`homecount`,`pagecount`,`feedback`,`friend`,`stow`)
                   VALUES ('$mid','0','0','0','0','0','0','0','0'); ";
            $dsql->ExecuteNoneQuery($membertjquery);
    
            //写入默认空间配置数据
            $spacequery = "INSERT INTO `#@__member_space`(`mid` ,`pagesize` ,`matt` ,`spacename` ,`spacelogo` ,`spacestyle`, `sign` ,`spacenews`)
                    VALUES('{$mid}','10','0','{$uname}的空间','','$space','',''); ";
            $dsql->ExecuteNoneQuery($spacequery);
			
            $cfg_ml->PutLoginInfo($mid);
            if(method_exists($cfg_ml,"DelCache") == TRUE) $cfg_ml->DelCache($mid);
            ShowMsg("成功登录，5秒钟后转向系统主页...","/user",0,2000);
            exit;
      }
}else{
	$cfg_ml->PutLoginInfo($memInfo['mid']);
    if(method_exists($cfg_ml,"DelCache") == TRUE) $cfg_ml->DelCache($cfg_ml->M_ID);
    ShowMsg("成功登录，5秒钟后转向系统主页...","/user",0,2000);
    exit;
}